package cn.daniellee.plugin.awa.core;

import cn.daniellee.plugin.awa.AuthWebApi;
import cn.daniellee.plugin.awa.model.Auth;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AuthCore {
    public static Auth parseAuth(String json) {
        try {
            Auth auth = new Gson().fromJson(json, Auth.class);
            if (auth != null && !Strings.isNullOrEmpty(auth.getName()) && !Strings.isNullOrEmpty(auth.getPassword())) return auth;
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            AuthWebApi.getInstance().getLogger().info(" ");
            AuthWebApi.getInstance().getLogger().info(("[AuthWebApi]An error occurred while json parse: " + json).replace("&", "§"));
            AuthWebApi.getInstance().getLogger().info(" ");
        }
        return null;
    }

    public static String decryptPassword(String text) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKey secretKey = new SecretKeySpec(AuthWebApi.getInstance().getAesKey().getBytes(StandardCharsets.UTF_8), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(text)), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            AuthWebApi.getInstance().getLogger().info(" ");
            AuthWebApi.getInstance().getLogger().info(("[AuthWebApi]An error occurred while password decrypt: " + text).replace("&", "§"));
            AuthWebApi.getInstance().getLogger().info(" ");
        }
        return null;
    }
}
